package com.baizhi.controller.front;

import cn.hutool.core.util.RandomUtil;
import com.baizhi.email.SendEmailUtil;
import com.baizhi.entity.*;
import com.baizhi.service.BookService;
import com.baizhi.service.CategoryService;
import com.baizhi.service.UserService;
import com.baizhi.util.JedisUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("front")
public class FrontController {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private UserService userService;
    @Autowired
    private BookService bookService;
    @Autowired
    private CategoryService categoryService;
    @RequestMapping("main")
    public String showMain(Model model){
        List<Category> categories = categoryService.selectChild();
        model.addAttribute("categories",categories);
        List<Book> recommends = bookService.recommends();
        model.addAttribute("recommendBooks",recommends);
        model.addAttribute("hotSaleBooks",bookService.hotSale());
        model.addAttribute("newBooks",bookService.newBooks());
        model.addAttribute("newHotSaleBooks",bookService.newHotBooks());
        return "forward:/front/main.jsp";
    }
    @RequestMapping("showOneBook")
    public String showOne(Integer id,Model model){
        Book book = bookService.showOne(id);
        model.addAttribute("book",book);
        return "forward:/front/book-detail.jsp";
    }
    @RequestMapping("searchBook")
    public String searchBooks(Model model,@RequestParam(defaultValue = "1")Integer pageNum,@RequestParam(defaultValue = "5")Integer pageSize,@RequestParam(defaultValue = "") String value){
        PageInfo<Book> bookPageInfo = bookService.selectBooks(pageNum, pageSize, value);
        model.addAttribute("pageInfo",bookPageInfo);
        model.addAttribute("value",value);
        return "forward:/front/search-book.jsp";
    }
    @RequestMapping("secondPage")
    public String secondPage(String sname,Model model,@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "5")Integer pageSize,
                             Integer sid,
                             Integer fid){
        List<Category> categories = categoryService.selectByParentId(fid);
        model.addAttribute("categories",categories);
        model.addAttribute("fid",fid);
        model.addAttribute("sid",sid);
        model.addAttribute("sname",sname);
        PageInfo<Book> bookPageInfo = bookService.selectBookByCategoryId(pageNum, pageSize, fid, sid);
        model.addAttribute("page",bookPageInfo);
        return "forward:/front/category-book.jsp";
    }
    @RequestMapping("cart/addCart")
    public String addCart(Integer id,HttpSession session) throws JsonProcessingException {
        Jedis jedis = JedisUtils.getJedis();
        String cart1 = jedis.get(""+id);
        Cart cart = null;
        if(cart1==null){
            cart= new Cart();
        }else {
            cart=objectMapper.readValue(cart1, Cart.class);
        }
        Map<Integer, CartItem> items = cart.getItems();
        if(!items.containsKey(id)){
            cart.setSize(cart.getSize()+1);
            CartItem cartItem = new CartItem();
            Book book = bookService.showOne(id);
            cartItem.setCount(1);
            cartItem.setBook(book);
            items.put(id,cartItem);
        }else {
            CartItem cartItem = items.get(id);
            cartItem.setCount(cartItem.getCount()+1);
        }
        double totalPrice= 0.0;
        double savePrice= 0.0;
        for (CartItem o : items.values()) {
            totalPrice += o.getBook().getDprice() * o.getCount();
            savePrice += (o.getBook().getPrice() * o.getCount()) - (o.getBook().getDprice() * o.getCount());
        }
        cart.setSavePrice(savePrice);
        cart.setTotalPrice(totalPrice);
        String s = objectMapper.writeValueAsString(cart);
        jedis.set(""+id,s);
        jedis.close();
        return "redirect:/front/cart/showCart.do?id="+id;
    }
    @RequestMapping("cart/showCart")
    public String showCart(Model model,Integer id) throws JsonProcessingException {
        Jedis jedis = JedisUtils.getJedis();
        String s = jedis.get(id + "");
        Cart cart = objectMapper.readValue(s, Cart.class);
        model.addAttribute("cart",cart);
        return "forward:/front/cart/cart.jsp";
    }
    @RequestMapping("cart/increaseCart")
    public String increaseCart(Integer id,HttpSession session) throws JsonProcessingException {
        Jedis jedis = JedisUtils.getJedis();
        String cart1 = jedis.get(""+id);
        Cart cart = objectMapper.readValue(cart1, Cart.class);
        Map<Integer, CartItem> items = cart.getItems();
        CartItem cartItem = items.get(id);
        Book book = bookService.showOne(id);
        if(book.getStock()> cartItem.getCount()){
            cartItem.setCount(cartItem.getCount()+1);
        }else {
            cartItem.setCount(cartItem.getCount());
            session.setAttribute("error","库存不够");
        }
        double totalPrice= 0.0;
        double savePrice= 0.0;
        for (CartItem o : items.values()) {
            totalPrice += o.getBook().getDprice() * o.getCount();
            savePrice += (o.getBook().getPrice() * o.getCount()) - (o.getBook().getDprice() * o.getCount());
        }
        cart.setSavePrice(savePrice);
        cart.setTotalPrice(totalPrice);
        String s = objectMapper.writeValueAsString(cart);
        jedis.set(""+id,s);
        jedis.close();
        session.setAttribute("cart",cart);
        return "redirect:/front/cart/showCart.do?id="+id;
    }
    @RequestMapping("cart/decreaseCart")
    public String decreaseCart(Integer id,HttpSession session) throws JsonProcessingException {
        Jedis jedis = JedisUtils.getJedis();
        String cart1 = jedis.get(""+id);
        Cart cart = objectMapper.readValue(cart1, Cart.class);
        Map<Integer, CartItem> items = cart.getItems();
        CartItem cartItem = items.get(id);
        if(cartItem.getCount()>1){
            cartItem.setCount(cartItem.getCount()-1);
        }else {
            items.remove(id);
            cart.setSize(0);
        }
        double totalPrice= 0.0;
        double savePrice= 0.0;
        for (CartItem o : items.values()) {
            totalPrice += o.getBook().getDprice() * o.getCount();
            savePrice += (o.getBook().getPrice() * o.getCount()) - (o.getBook().getDprice() * o.getCount());
        }
        cart.setSavePrice(savePrice);
        cart.setTotalPrice(totalPrice);
        String s = objectMapper.writeValueAsString(cart);
        jedis.set(""+id,s);
        jedis.close();
        session.setAttribute("cart",cart);
        return "redirect:/front/cart/showCart.do?id="+id;
    }
    @RequestMapping("cart/removeCart")
    public String removeCart(Integer id,HttpSession session) throws JsonProcessingException {
        Jedis jedis = JedisUtils.getJedis();
        String cart1 = jedis.get(""+id);
        Cart cart = objectMapper.readValue(cart1, Cart.class);
        Map<Integer, CartItem> items = cart.getItems();
        items.remove(id);
        double totalPrice= 0.0;
        double savePrice= 0.0;
        for (CartItem o : items.values()) {
            totalPrice += o.getBook().getDprice() * o.getCount();
            savePrice += (o.getBook().getPrice() * o.getCount()) - (o.getBook().getDprice() * o.getCount());
        }
        cart.setSavePrice(savePrice);
        cart.setTotalPrice(totalPrice);
        cart.setSize(0);
        String s = objectMapper.writeValueAsString(cart);
        jedis.set(""+id,s);
        jedis.close();
        session.setAttribute("cart",cart);
        return "redirect:/front/cart/showCart.do?id="+id;
    }
    @RequestMapping("userLogin")
    public String userLogin(HttpSession session,User user1){
        try{
            userService.userLogin(user1);
            User user = userService.selectUserByEmail(user1.getEmail());
            session.setAttribute("user",user);
            session.setAttribute("login",true);
            return "redirect:/front/main.do";
        }catch (Exception e){
            session.setAttribute("msg",e.getMessage());
            return "redirect:/front/login.jsp";
        }
    }
    @RequestMapping("register")
    public String userRegister(HttpSession session,User user,String password2,String validateCode){
        String s = RandomUtil.randomString(6);
        String realCode = (String)session.getAttribute("realCode");
        if(realCode.equalsIgnoreCase(validateCode)!=true){
            return "redirect:/front/register.jsp";
        }
        try {
            user.setStatus(-1);
            user.setCode(s);
            user.setSalt("中华");
            user.setCreateDate(new Date());
            session.setAttribute("email",user.getEmail());
            userService.userRegister(user,password2);
            SendEmailUtil.sendCode(user.getEmail(),s);
            session.setAttribute("code",s);
            return "redirect:/front/validateEmail.jsp";
        }catch (Exception e){
            System.out.println("e.getMessage() = " + e.getMessage());
            session.setAttribute("msg",e.getMessage());
            return "redirect:/front/register.jsp";
        }
    }
    @RequestMapping("activeUser")
    public String activeUser(String email,String code,HttpSession session){
        User user = userService.selectUserByEmail(email);
        if(user.getCode().equals(code)){
            user.setStatus(1);
            userService.updateUser(user);
            session.setAttribute("nickname",user.getNickname());
            return "redirect:/front/registerEnd.jsp";
        }else {
            session.setAttribute("msg","验证码不正确,请再次输入");
            return "redirect:/front/validateEmail.jsp";
        }
    }
}
